package top.jacktgq.file

import groovy.xml.MarkupBuilder

/**
 @Author CandyWall
 @Date 2021/4/28--9:38
 @Description 生成xml
 */
/* 目标：生成如下xml数据
<langs type='current' count='3' mainstream='true'>
  <language flavor='static' version='1.5'>java</language>
  <language flavor='dynamic' version='1.6.0'>groovy</language>
  <language flavor='dynamic' version='1.9'>javascript</language>
</langs>
 */
def sw = new StringWriter()
// 用来生成xml的核心类
def xmlBuilder = new MarkupBuilder(sw)
// 根节点langs创建成功
xmlBuilder.langs(type: 'current', count: '3', mainstream: 'true') {
    language(flavor: 'static', version: '1.5', 'java') {
        age('16')
    }
    language(flavor: 'dynamic', version: '1.6.0', 'groovy')
    language(flavor: 'dynamic', version: '1.9', 'javascript') {
        age('16')
    }
}

println sw

// 将对象转成xml
// 对应xml数据中的langs结点
class Langs {
    String type = 'current'
    int count = 3
    boolean mainstream = true
    def Languages = [
        new Language(flavor: 'static', version: '1.5', value: 'Java'),
        new Language(flavor: 'static', version: '1.5', value: 'Groovy'),
        new Language(flavor: 'static', version: '1.5', value: 'Javascript')
    ]
}
// 对应xml数据中的language结点
class Language {
    String flavor
    String version
    String value
}

sw = new StringWriter()
xmlBuilder = new MarkupBuilder(sw)
def langs = new Langs()
xmlBuilder.langs(type: langs.type, count: langs.count, mainstream: langs.mainstream) {
    langs.languages.each {
        lang -> language(flavor: lang.flavor, version: lang.version, lang.value)
    }
}
println sw

